
chrome.runtime.onMessage.addListener(
    async function (request, sender, sendResponse) {
        //加载css
        loadCss();

        switch (request.action) {
            case "appendRoleWindow":
                await appendRoleWindow();
                break;
            default:
                break;
        }
    }
);



async function appendRoleWindow() {
    //加载自定义页面_规则页面
    await loadCustomPopupPage();

    //取消
    $('#rule-undo').click(function() {
        $('#rule-window-container').remove();
    });

    //单选
    $('#method-0').click(function() {
        $('#rule-window-container').hide();
        $(document).mousemove(function(e) {
            var target = e.target;
            var xpath = getElementXPath(target);
            console.log('Mouseover XPath: ', xpath);
            var result = document.evaluate(xpath, document, null, XPathResult.ANY_TYPE, null);
            var node = result.iterateNext();
            if ($(node).length > 0) {
                $('[highlight-m=m]').removeAttr('highlight-m');
                $(node).attr('highlight-m', 'm');
            }
        });
    });

    //多选
    $('#method-1').click(function() {
        $('#rule-window-container').hide();
        var lastXpath;
        $(document).mousemove(function(e) {
            var target = e.target;
            var xpath = getElementXPath(target);
            console.log('Mouseover XPath: ', xpath);
            if (xpath == lastXpath)
                return;
            lastXpath = xpath;

            $('[highlight-m=m]').removeAttr('highlight-m');
            var result = document.evaluate(xpath, document, null, XPathResult.ANY_TYPE, null);
            var nodes = [];
            while (node = result.iterateNext()) {
                nodes.push(node);
            }
            nodes.forEach(function(node) {
                $(node).attr('highlight-m', 'm');
            });

        });
    });
}

async function loadCustomPopupPage() {
    var popupHTMLUrl = chrome.runtime.getURL('custom_popup.html');
    var response = await fetch(popupHTMLUrl);
    var htmlContent = await response.text();
    $('body').append('<div id="rule-window-container"></div>');
    $('#rule-window-container').html(htmlContent);
}

function loadCss() {
    //动态加载名为content-script.css的CSS文件
    var cssUrl = chrome.runtime.getURL('content-script.css');
    $.loadCSS = function (href) {
        if ($('#packageCss').length <= 0) {
            $('<link id="packageCss">')
                .appendTo('head')
                .attr({
                    type: 'text/css',
                    rel: 'stylesheet',
                    href: href // 这里填写你想要加载的CSS文件路径
                });
        }
    };
    $.loadCSS(cssUrl);
}

//1. 把标签中的class加到XPATH中
//2. 把XPATH中的所有数组去掉
//3. 判断XPATH从哪个标签开始
function getElementXPath(element) {

    if (element && element.id)
        return '//*[@id="' + element.id + '"]';
    else
        return getElementTreeXPath(element);
}

function getElementTreeXPath(element) {
    var paths = [];
    for (; element && element.nodeType == Node.ELEMENT_NODE; element = element.parentNode) {
        var index = 0;
        for (var sibling = element.previousSibling; sibling; sibling = sibling.previousSibling) {
            // Ignore document type declaration.
            if (sibling.nodeType == Node.DOCUMENT_TYPE_NODE)
                continue;
            if (sibling.nodeName == element.nodeName)
                ++index;
        }

        var tagName = element.tagName.toLowerCase();
        var pathIndex = (index ? '[' + (index + 1) + ']' : '');
        paths.splice(0, 0, tagName + pathIndex);
    }

    return paths.length ? '/' + paths.join('/') : null;
}




